import { defineAppConfig } from 'ice';
import { defineAuthConfig } from '@ice/plugin-auth/types';
import { defineStoreConfig } from '@ice/plugin-store/types';
import { defineRequestConfig } from '@ice/plugin-request/types';
import { clearAuthAndRedirect } from './utils/auth';
import { requestConfig as config } from './utils/request';

// Request config
export const requestConfig = defineRequestConfig(() => config);

// App config
export default defineAppConfig(() => ({
  app: {
    rootId: 'ice-container',
  },
  router: {
    type: 'browser',
    basename: '/',
    beforeEach: (to, from) => {
      // 白名单路由，不需要验证token
      const whiteList = ['/login', '/register'];
      
      if (!whiteList.includes(to.pathname)) {
        const token = localStorage.getItem('token');
        if (!token) {
          clearAuthAndRedirect();
          return false;
        }
        
        // 可以添加token有效性验证
        try {
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
          if (!userInfo.id) {
            clearAuthAndRedirect();
            return false;
          }
        } catch (error) {
          clearAuthAndRedirect();
          return false;
        }
      }
      return true;
    },
  },
}));

// Auth config
export const authConfig = defineAuthConfig(() => ({
  initialAuth: {
    admin: false,
    user: false,
  },
}));

// Store config
export const storeConfig = defineStoreConfig(() => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  return {
    initialStates: {
      user: {
        currentUser: userInfo,
      },
    },
  };
});

